package com.yin.jia.liang.service;

import com.yin.jia.liang.dao.GoodsMapper;
import com.yin.jia.liang.dao.GoodsPlMapper;
import com.yin.jia.liang.dao.UserMapper;
import com.yin.jia.liang.entity.*;
import com.yin.jia.liang.vo.GoodsPlVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
public class GoodsPlService {

    @Autowired
    GoodsPlMapper goodsPlMapper;
    @Autowired
    GoodsMapper goodsMapper;
    @Autowired
    UserMapper userMapper;

    public List<GoodsPlVo> findByUserId(int userId) {
        GoodsPlExample ue = new GoodsPlExample();
        GoodsPlExample.Criteria criteria = ue.createCriteria();
        criteria.andUserIdEqualTo(userId);
        ue.setOrderByClause("id desc");
        List<GoodsPl> g = goodsPlMapper.selectByExampleWithBLOBs(ue);

        List<GoodsPlVo> goodsPlVos = E2Vo(g);

        return goodsPlVos;
    }

    public List<GoodsPlVo> findByGoodsId(int goodsId) {
        GoodsPlExample ue = new GoodsPlExample();
        GoodsPlExample.Criteria criteria = ue.createCriteria();
        criteria.andGoodsIdEqualTo(goodsId);
        ue.setOrderByClause("id desc");
        List<GoodsPl> g = goodsPlMapper.selectByExampleWithBLOBs(ue);

        List<GoodsPlVo> goodsPlVos = E2Vo(g);

        return goodsPlVos;
    }


    private List<GoodsPlVo> E2Vo (List<GoodsPl> goodsPls) {
        List<GoodsPlVo> goodsPlVos = new ArrayList<>();

        for (GoodsPl g : goodsPls) {
            GoodsPlVo vo = new GoodsPlVo();

            Goods goods = goodsMapper.selectByPrimaryKey(g.getGoodsId());
            User user = userMapper.selectByPrimaryKey(g.getUserId());

            vo.setGoods(goods);
            vo.setUser(user);
            vo.setUserId(g.getUserId());
            vo.setId(g.getId());
            vo.setGoodsId(g.getGoodsId());
            vo.setCreateAt(g.getCreateAt());
            vo.setContent(g.getContent());

            goodsPlVos.add(vo);
        }
        return goodsPlVos;
    }

    public Integer save(GoodsPl goodsPl) {
        int i = goodsPlMapper.insert(goodsPl);
        return i;
    }



    public Integer delete(Integer id) {
        return goodsPlMapper.deleteByPrimaryKey(id);
    }
}
